const fs = require('fs');
let urlArray = []

function addMapping(router, mapping) {
  for (let url in mapping) {
    urlArray.push(url);
    if (url.startsWith('GET ')) {
      let path = url.substring(4);
      router.get(path, mapping[url]);
      console.log(`register URL mapping: GET ${path}`);
    } else if (url.startsWith('POST ')) {
      let path = url.substring(5);
      router.post(path, mapping[url]);
      console.log(`register URL mapping: POST ${path}`);
    } else if (url.startsWith('PUT ')) {
      let path = url.substring(4);
      router.put(path, mapping[url]);
      console.log(`register URL mapping: PUT ${path}`);
    } else if (url.startsWith('DELETE ')) {
      let path = url.substring(7);
      router.del(path, mapping[url]);
      console.log(`register URL mapping: DELETE ${path}`);
    } else {
      console.log(`invalid URL: ${url}`);
    }
  }
}

/* 获取所有dir文件夹下以.js结尾的文件 */
function addControllers(router, dir) {
  /* 同步函数读取文件夹中的文件 */
  fs.readdirSync(__dirname + '/' + dir).filter((f) => {
    return f.endsWith('.js');
  }).forEach((f) => {
    console.log(`process controller: ${f}...`);
    let mapping = require(__dirname + '/' + dir + '/' + f);
    console.log(mapping);
    addMapping(router, mapping);
  });
  /* 用于检验是否有重复的路由 */
  let urlSet = new Set(urlArray);
  if (urlArray.length !== urlSet.size) {
    throw ('注意有重复的路由');
  }
}

module.exports = function (dir) {
  let
    controllers_dir = dir || 'controllers',
    router = require('koa-router')();
  addControllers(router, controllers_dir);
  return router.routes();
};